package com.dmall.ssm.utils;

import com.dmall.ssm.pojo.Dog;
import com.dmall.ssm.pojo.Pets;
import com.dmall.ssm.pojo.User;
import org.springframework.beans.BeanUtils;
import org.springframework.cglib.beans.BeanCopier;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

public class BeanCopyUtils {

    /**
     * BeanCopier的缓存
     */
    static final ConcurrentHashMap<String, BeanCopier> BEAN_COPIER_CACHE = new ConcurrentHashMap<>();

    /**
     * BeanCopier的copy
     * @param source 源文件的
     * @param target 目标文件
     */
    public static void copy(Object source, Object target) {
        String key = genKey(source.getClass(), target.getClass());
        BeanCopier beanCopier;
        if (BEAN_COPIER_CACHE.containsKey(key)) {
            beanCopier = BEAN_COPIER_CACHE.get(key);
        } else {
            beanCopier = BeanCopier.create(source.getClass(), target.getClass(), false);
            BEAN_COPIER_CACHE.put(key, beanCopier);
        }
        beanCopier.copy(source, target, null);
    }

    /**
     * 生成key
     * @param srcClazz 源文件的class
     * @param tgtClazz 目标文件的class
     * @return string
     */
    private static String genKey(Class<?> srcClazz, Class<?> tgtClazz) {
        return srcClazz.getName() + tgtClazz.getName();
    }

    public static void main(String[] args) {
        User user1 = new User();
        user1.setId(1);
        user1.setLoginName("zhangsan");
        user1.setRealName("张三");
        user1.setPassword("zhangsan");
        user1.setGender(1);
        user1.setBirth(new Date());
        user1.setDesc("这个人很懒，什么都没留下");
        Pets pets = new Dog();
        pets.setAge(1);
        pets.setName("旺财");
        user1.setPets(pets);

        User user2 = new User();
        BeanCopyUtils.copy(user1, user2);
        System.out.println(user2);

        User user3 = new User();
        BeanUtils.copyProperties(user1, user3);
        System.out.println(user3);
    }
}
